using UnityEngine;
using System.Collections;

public class InteractThing : InteractObject
{
    public float movePower = 6f;

    private MonoBehaviour   sender;
    private Vector3         lastMove;
    private Quaternion      rotationOffset;
    private float           lengthOffset;
    private bool            isFixed = false;
    private bool            useGravityOld;
    private TextMesh        text;

    public void Start()
    {
        text = gameObject.GetComponentInChildren<TextMesh>();
    }

    public void LateUpdate()
    {
        if (isFixed)
        {
            if (Input.GetKeyUp(interactButton))
            {
                isFixed = false;
                text.text = "Released";

                if (rigidbody != null)
                {
                    rigidbody.useGravity = useGravityOld;
                    rigidbody.velocity = lastMove * movePower * movePower;
                }

                sender = null;
            }
            else
            {
                Vector3 from    = transform.position;
                Vector3 to      = sender.transform.position;

                // debug only
                Debug.DrawLine(to, to + sender.transform.up * 5, Color.green);

                to += sender.transform.forward * lengthOffset;

                // debug only
                Debug.DrawLine(sender.transform.position, to, Color.magenta);
                Debug.DrawLine(from, to, Color.cyan);

                Vector3 result = Vector3.Lerp(from, to, Time.deltaTime * movePower);
                lastMove = result - transform.position;
                transform.position = result;

                // transform.rotation = sender.transform.rotation;
                rigidbody.velocity = Vector3.zero;
            }
        }
    }

    public void Update()
    {
        if (!text.text.Equals("Fixed"))
            text.text = "I'm here";
    }

    override public void Interact(MonoBehaviour sender)
    {
        if (!text.text.Equals("Fixed"))
            text.text = "I'm ready";

        if (Input.GetKeyDown(interactButton))
        {
            text.text = "Fixed";
            isFixed = true;
            lengthOffset = (sender.transform.position - transform.position).magnitude;
            rotationOffset = transform.rotation;
            rotationOffset.Set(1, 1, 1, 1);

            if (rigidbody != null)
            {
                useGravityOld = rigidbody.useGravity;
                rigidbody.useGravity = false;
            }

            this.sender = sender;
        }
    }
}
